
import lxml
import requests
from lxml import etree


# 获取登陆参数(内网登陆加密了，在web端有一个js自动解密的一个过程，但爬虫得自己写一个获取参数并解密)



def get_parameter():
    # 请求头，作用是伪装为浏览器访问
    headers = {
        'Host': 'class.sise.com.cn:7001',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
        'Referer': 'http://class.seig.edu.cn:7001/sise/',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.8'
    }
    url = 'http://class.seig.edu.cn:7001/sise/'
    # 发送请求
    request = requests.get(url, headers=headers)
    # 返回响应response
    response = request.text
    # 将文本转化为HTML便于Xpath解析
    e = etree.HTML(response)
    # 使用xpath解析response
    # 获得3个随机参数，这是破解内网登陆的一步
    name = e.xpath('//div/form/input[1]/@name')[0]
    value = e.xpath('//div/form/input[1]/@value')[0]
    random = e.xpath('//div/form/input[2]/@value')[0]
    return name, value, random


# 登陆并爬取相关数据
def land_sise_get_info(url, user, pw):
    # username = input("学号")
    # password = input("密码")
    username = user
    password = pw

    # 调用函数得到3个随机变量
    name, value, random = get_parameter()
    # 在进行正式登陆时，要确保与上次保持会话，其输入的3个随机变量才会与上次相同
    session = requests.Session()
    # 请求头，作用是伪装为浏览器访问
    headers = {
        'Host': 'class.sise.com.cn:7001',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
        'Referer': 'http://class.sise.com.cn:7001/sise/',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.8'
    }

    # 登录URL
    login_url = 'http://class.seig.edu.cn:7001/sise/login_check_login.jsp'
    # 登陆时需要传入3个上次得到的变量和账号密码
    login_dates = {
        name: value,
        'random': random,
        'username': username,
        'password': password
    }
    # 发送请求
    session.post(url=login_url, data=login_dates, headers=headers)

    target_url = url
    # 获取信息
    target_request = session.get(url=target_url, headers=headers)

    # 解析
    target_response = target_request.text

    # 将课程表的html全部保存下来
    # save_info(target_response)

    # 打开爬取到的html
    # os.system('mysise.html')

    # 打印出课程表
    a = get_kcb_info(target_response)
    return a


# 保存爬取到的数据
def save_info(info):
    with open('mysise.html', 'w', encoding='utf-8') as f:
        f.write(info)
        f.close()


week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天']
time = ['09:00 - 10:20', '10:40 - 12:00', '12:30 - 13:50', '14:00 - 15:20', '15:30 - 16:50', '17:00 - 18:20',
        '19:00 - 20:20', '20:30 - 21:50']


# 解析爬取到的数据
def get_kcb_info(info):
    e = etree.HTML(info)
    a = []
    # 爬取到tbody时要将tbody标签删除
    s = 0
    for x in range(2, 10):
        name = e.xpath('/html/body/form/table[5]/tr[%d]/*' % x)
        time_new = time[s]
        s = s + 1
        for y in range(len(name) - 1):
            b = []
            kc = name[y + 1].text
            week_new = week[y]
            # ' '是表格内容为空的情况
            if kc != ' ':
            #     b.append(week_new)
            #     b.append(time_new)
            #     b.append("无")
            #     b.append("无")
            #     b.append("无")
            #     b.append("无")
            #     b.append("无")
            #     a.append(b)
            # else:
                if len(kc.split(',')) > 1:
                    for class_num in range(len(kc.split(', '))):
                        b = []
                        class_1 = kc.split(', ')[class_num]
                        class_info, class_id, class_teacher, class_week, claas_room = class_new(class_1)
                        b.append(week_new)
                        b.append(time_new)
                        b.append(class_info)
                        b.append(class_id)
                        b.append(class_teacher)
                        b.append(class_week)
                        b.append(claas_room)
                        a.append(b)
                else:
                    class_info, class_id, class_teacher, class_week, claas_room = class_new(kc)
                    b.append(week_new)
                    b.append(time_new)
                    b.append(class_info)
                    b.append(class_id)
                    b.append(class_teacher)
                    b.append(class_week)
                    b.append(claas_room)
                    a.append(b)
    return a


import re


def class_replace(class_new):
    class_new = class_new.replace('(', '')
    class_new = class_new.replace(')', '')
    class_new = class_new.replace('[', '')
    class_new = class_new.replace(']', '')
    class_new = class_new.replace(' ', '')
    class_1 = re.split('([A-Z0-9_]+)', class_new, 1)  # 按课程班级分割
    class_id = class_1[1]  # 课程代号
    class_teacher = re.split('(\d+.)', class_1[2], 1)[0]  # 课程老师名
    class_week = re.split('(\d+.)', class_1[2], 1)[1]  # 上课周数
    claas_room = re.split('(\d+.)', class_1[2], 1)[2]  # 上课教室
    return class_id, class_teacher, class_week, claas_room


def class_new(class_file):
    if class_file.count('(') > 1:
        # 将课程信息（第二名称）（其他信息）处理成 课程信息（其他信息）
        class_info = class_file[:class_file.find(')') + 1]  # 课程信息(名字)
        class_new = class_file[class_file.find(')') + 1:]  # (其他信息)
        class_id, class_teacher, class_week, claas_room = class_replace(class_new)
        return class_info, class_id, class_teacher, class_week, claas_room
    elif class_file.count('(') == 1:
        class_info = class_file[:class_file.find('(')]  # 课程信息(名字)
        class_new = class_file[class_file.find('('):]  # 课程信息(名字)
        class_id, class_teacher, class_week, claas_room = class_replace(class_new)
        return class_info, class_id, class_teacher, class_week, claas_room


if __name__ == '__main__':
    a = land_sise_get_info(url='http://class.seig.edu.cn:7001/sise/module/student_schedular/student_schedular.jsp',
                           user="2040231145",
                           pw="20440883106016@SEIG!sise"
                           )
    for i in a:
        week = i[0]
        time = i[1]
        class_info = i[2]
        class_id = i[3]
        class_teacher = i[4]
        class_week = i[5]
        claas_room = i[6]
        print(week, time[:5], time[8:], class_info, class_id, class_teacher, class_week, claas_room)
